let unityInstance = null
const channel = new BroadcastChannel(sessionStorage.getItem('channelKey'))
const PlatformType = {
  Web2Unity: 0,
  Unity2Web: 1,
  Android: 2,
  IOS: 3
}

function setSize () {
  const unity_canvas = document.getElementById('unity-canvas')
  if (!unity_canvas) return
  unity_canvas.style.width = window.innerWidth + 'px'
  unity_canvas.style.height = window.innerHeight + 'px'
  // console.log('canvas width:', window.innerWidth, 'height:', window.innerHeight)
}

setSize()

function queueMessage (instance) {
  unityInstance = instance
  setupKeyListeners()
  window.addEventListener('message', onMessage)
  // delaySend(instance, 'run', 'startPart', [])
}
//测试下载
function setupKeyListeners() {
  document.addEventListener('keydown', (event) => {
    if (event.key.toLowerCase() === 'l') { // 不区分大小写
      console.log('加载模型！!!!!!')
      if (unityInstance) { // 确保 Unity 实例已初始化
        // 方式1：直接发送消息到 Unity
        send(unityInstance, 3, { url: 'http://localhost:8089/download/',filename:'1742954555351-堆垛机.fbx' })
      }
    }
  });
}


function ReceiveMessageFromUnity (message) {
  let data = JSON.parse(message)
  if (data.platform && data.platform === PlatformType.Unity2Web) {
    window.parent.postMessage(data, '*')
  }
}

function splitMessage (type, message) {
  let strMessage = JSON.stringify(message)
  let datas = []
  let length7500 = strMessage.length / 7500
  let mLength = Math.floor(length7500) === length7500 ?
    length7500 - 1 : Math.floor(length7500)
  for (let i = 0; i <= mLength; i++) {
    let str = i === mLength ?
      strMessage.slice(i * 7500, strMessage.length) : strMessage.slice(i * 7500, (i + 1) * 7500)
    datas.push({ type: type, index: i, size: mLength + 1, data: str })
  }
  return datas
}

function onMessage (event) {
  // if (event.origin !== 'https://parentdomain.com') return;
  let data = event.data
  if (data.platform && data.platform === PlatformType.Unity2Web) {
    return
  }
  send(unityInstance, data.type, data.data)
  // unityInstance.SendMessage('ReceiveWeb', 'ReceiveMessageFromJs', JSON.stringify(data))
}

function delaySend (instance, type, key, message) {
  setTimeout(() => {
    let datas = splitMessage(type, message)
    try {
      for (let data of datas) {
        instance.SendMessage('ReceiveWeb', 'ReceiveMessageFromJs', JSON.stringify(data).trim())
        // console.log('delaySend', JSON.stringify(data))
      }
    } catch (e) {
      // debugger
    }
  }, 50)
}

function send (instance, type, message) {
  let datas = splitMessage(type, message)
  for (let data of datas) {
    instance.SendMessage('ReceiveWeb', 'ReceiveMessageFromJs', JSON.stringify(data).trim())
  }
}

function run (instance) {
  let data = { type: 'run', data: { startPart: [] } }
  // setTimeout(() => {
  //   instance.SendMessage('ReceiveWeb', 'ReceiveMessageFromJs',
  //     JSON.stringify(data.startPart))
  // }, 100)
}
